// pages/index/class/class.js
var app = getApp()
const request = require('../../../utils/request');
Page({
  data: {
    videoList: [],
    videoIndex: null,
    page: 1,
    count: 10,
    type: 1,
    active: 0,
    order_sn: '',
    total_amount: ''
  },

  onLoad() {
    if (!app.d.openId || app.d.openId == '') {
      this.getOpenId();
    }
    this.getVideoList()
  },
  getOpenId() {
    request.get('get_openid', { token: wx.getStorageSync("token") })
      .then(res => {
        wx.hideLoading()
        app.d.openId = res.data[0].openid
      })
      .catch(error => {
        wx.showToast({
          icon: 'none',
          title: error.msg && error.msg
        })
      })
      .finally(_ => {
        
      })
  },
  onTavChange(e){
    this.setData({
      type: e.detail.index + 1
    })
    this.getVideoList()

    if (typeof this.data.videoIndex === 'number') {
      const videoContextPrev = wx.createVideoContext('video' + this.data.videoIndex)
      videoContextPrev.stop()
      this.setData({
				videoIndex: null
			})
    }
  },

  //获取视频列表
  getVideoList(){
    const data = {
      type: this.data.type,
      page: this.data.page
    }
    request.get('video_list', data)
      .then(res => {
        wx.hideLoading()
        if (res.data && res.data.length) {
          const data = res.data.map(v => {
            Object.assign(v, {
              coverimg: 'https://goss.veer.com/creative/vcg/veer/800water/veer-146156021.jpg',
              content: 'http://wxsnsdy.tc.qq.com/105/20210/snsdyvideodownload?filekey=30280201010421301f0201690402534804102ca905ce620b1241b726bc41dcff44e00204012882540400&bizid=1023&hy=SH&fileparam=302c020101042530230204136ffd93020457e3c4ff02024ef202031e8d7f02030f42400204045a320a0201000400'
            })
            return v
          })  
          
          this.setData({
            videoList: data
          })
        }
      })
      .catch(error => {
        wx.showToast({
          icon: 'none',
          title: error.msg && error.msg
        })
      })
      .finally(_ => {
        
      })
  },

  // 看视频
  videoPlay(e) {
		const index = e.currentTarget.dataset['index'];

		if (!this.data.videoIndex) { // 没有播放时播放视频
			this.setData({
				videoIndex: index
			})
			const videoContext = wx.createVideoContext('video' + index)
			videoContext.play()
		} else {
			//停止正在播放的视频
			const videoContextPrev = wx.createVideoContext('video' + this.data.videoIndex)
			videoContextPrev.stop()
			//将点击视频进行播放
			this.setData({
				videoIndex: index
			})
			const videoContextCurrent = wx.createVideoContext('video' + index)
			videoContextCurrent.play()
		}
  },

  // 付费视频
  payVideo(e) {
    const id = e.currentTarget.dataset.id
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确定付费观看视频？',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          that.createOrder(id);
          // that.goPay();
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  // 生成订单
  createOrder: function(id) {

    wx.showLoading({
      title: '加载中',
    })
    request.get('buy_video', { token: wx.getStorageSync("token"), id: id })
      .then(res => {
        this.setData({
          order_sn: res.oid[0].order_sn,
          total_amount: parseInt(res.oid[0].total_amount)
        })
        console.log(res.oid[0], this.data.order_sn, this.data.total_amount)
        this.goPay();
      })
      .catch(error => {
        wx.showToast({
          icon: 'none',
          title: error.msg && error.msg
        })
      })
      .finally(_ => {
        // wx.hideLoading()
      })
  },
  // 支付
  goPay() {
    const data = {
      order_sn: this.data.order_sn,
      openid: app.d.openId,
      total_amount: this.data.total_amount
    }
    console.log(data)
    wx.request({
      url: app.d.severUrl + 'pay_video',//这个链接是后端写的  
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: "POST",
      data: data,
      success: function (res) {
        wx.hideLoading()

        // return;
        if (res.data.code == 0) {
          wx.showToast({
            title: res.data.msg,
            icon: 'loading'
          })
        }
        if (res.data.state == 1) {
          // --------- 订单生成成功，发起支付请求 ------------------
          // wx.showLoading({
          //   title: '加载中',
          // })
          wx.requestPayment({
            timeStamp: res.data.timeStamp,
            nonceStr: res.data.nonceStr,   //字符串随机数
            package: res.data.package,
            signType: res.data.signType,
            paySign: res.data.paySign,
            'success': function (res) {
              // wx.hideLoading()
              console.log(res);
              console.log(res.errMsg);
              console.log(res.errMsg.requestPayment);
              if (res.errMsg == 'requestPayment:ok') {
                this.onShow()
              } else {
                console.log('取消')
                wx.showToast({
                  title: res.data.msg,
                  icon: 'loading'
                })
              }    //requestPayment:ok==>调用支付成功
            },
            'fail': function (res) {
              console.log(res.errMsg);
              console.log(111);
            },
            'complete': function (res) {
              console.log(res.errMsg);
            }
          })
        } else if (res.data.state == 0) {
          wx.showToast({
            title: res.data.Msg,
            icon: 'fail',
            duration: 1000
          })
        } else {
          wx.showToast({
            title: '系统繁忙，请稍后重试~',
            icon: 'fail',
            duration: 1000
          })
        }
      }
    })
  },  

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this;
    if (that.data.page * that.data.count > that.data.classList.length && that.data.classList.length > 0) {
      wx.showToast({
        title: '已加载全部数据',
      })
    } else if (that.data.classList.length > 0) {
      that.data.page = that.data.page + 1;
      that.getVideoList();
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})